package logic

import (
	"context"
	"fmt"
	"shopping-mall/models"
	"shopping-mall/pkg"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ResetPasswordLogic) ResetPassword(in *shopping_rpc.ResetPasswordRequest) (*shopping_rpc.ResetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("account = ?", in.Phone).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号未注册")
	}
	key := fmt.Sprintf("%s:%s", "RP", in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.Password == pkg.MD5(in.Password) {
		return nil, fmt.Errorf("新密码与旧密码不得相同")
	}
	user.Password = pkg.MD5(in.Password)
	if models.DB.Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &shopping_rpc.ResetPasswordResponse{}, nil
}
